/*************************************************************************
	> File Name: db.java
	> Author: Potter
	> Mail: tobewhatwewant@gmail.com 
	> Created Time: 2014年06月02日 星期一 11时22分05秒
 ************************************************************************/
import java.io.*;

public class db { 
    private ObjectInputStream in;
    private ObjectOutputStream out;

    db() throws Exception {
        out = new ObjectOutputStream(new FileOutputStream("db.txt"));
        in = new ObjectInputStream(new FileInputStream("db.txt"));
    }

    public static void main(String[] args) throws Exception {
        Person per = new Person(1, "Potter", 20);
        Person per2 = new Person(2, "Kate", 21);

        db d = new db();
        d.add(per);
        d.add(per2);
        // d.list();

        per2.setName("BigKate");
        per2.setAge(22);

        d.update(per2);
        d.list();
    }

    public void add(Person per) throws Exception {
        out.writeObject(per);
    }

    public void update(Person per) throws Exception {
        while(true) {
            Person person = (Person)in.readObject();
            if(person.getId() == per.getId()) {
                person.setAge(per.getAge());
                person.setName(per.getName());

                out.writeObject(person);
                break;
            }
            out.writeObject(person);
        }
    }

    public void list() throws Exception {
        Person per = null;
        try {
            while((per = (Person)in.readObject()) != null) {
                System.out.println(per);
            }
        } catch (Exception e) {

        }
    }
}

class Person implements Serializable {
    private int id;
    private String name;
    private int age;

    Person(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return id+" : "+name+" : "+age;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}
